package me.zhengjie.controller;

import io.prestosql.sql.SqlFormatter;
import io.prestosql.sql.parser.ParsingException;
import io.prestosql.sql.parser.ParsingOptions;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.tree.Statement;
import me.zhengjie.annotation.AnonymousAccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static me.zhengjie.util.JsonUtil.writeJSON;
import static io.prestosql.sql.parser.ParsingOptions.DecimalLiteralTreatment.AS_DOUBLE;


/**
 * sql美化
 */
@RestController
public class FormatSqlController {
	private static final Logger LOGGER = LoggerFactory.getLogger(FormatSqlController.class);
	@PostMapping("format")
	@AnonymousAccess
	public void format(String query, HttpServletResponse response)  {
		Map<String, Object> responseBody = new HashMap<>();
		try {
			if (query != null) {
				responseBody.put("formattedQuery", formatQuery(query));
			}
		} catch (Throwable e) {
			LOGGER.error(e.getMessage(), e);
			if (e instanceof ParsingException) {
				responseBody.put("errorLineNumber", ((ParsingException) e).getLineNumber());
			}
			responseBody.put("error", e.getMessage());
		}
		writeJSON(response, responseBody);
	}

	private String formatQuery(String query) {
		SqlParser sqlParser = new SqlParser();
		Statement statement = sqlParser.createStatement(query, new ParsingOptions(AS_DOUBLE));
		return SqlFormatter.formatSql(statement, Optional.empty());
	}
}
